<?php
/**
 * Created by JetBrains PhpStorm.
 * User: tcore
 * Date: 15.01.12
 * Time: 2:53
 * To change this template use File | Settings | File Templates.
 */
class AHelper
{
	public static function jsonEncode($a=false)
	{
		if (is_null($a)) return 'null';
		if ($a === false) return 'false';
		if ($a === true) return 'true';
		if (is_scalar($a))
		{
			if (is_float($a))
			{
				// Always use "." for floats.
				$a = str_replace(",", ".", strval($a));
			}
			// All scalars are converted to strings to avoid indeterminism.
			// PHP's "1" and 1 are equal for all PHP operators, but
			// JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend,
			// we should get the same result in the JS frontend (string).
			// Character replacements for JSON.
			static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'),
				array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
			return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
		}
		$isList = true;
		for ($i = 0, reset($a); $i < count($a); $i++, next($a))
		{
			if (key($a) !== $i)
			{
				$isList = false;
				break;
			}
		}
		$result = array();
		if ($isList)
		{
			foreach ($a as $v) $result[] = self::jsonEncode($v);
			return '[ ' . join(', ', $result) . ' ]';
		}
		else
		{
			foreach ($a as $k => $v) $result[] = self::jsonEncode($k).': '.self::jsonEncode($v);
			return '{ ' . join(', ', $result) . ' }';
		}
	}

	public static function arrayToJSObject($array, $varName, $sub = false )
	{
		$jsArray = $sub ? $varName . "{" : $varName . " = {";
		$varName = "$varName";
		reset ($array);

		// Loop through each element of the array
		while (list($key, $value) = each($array)) {
			$jsKey = "'" . $key . "':";

			if (is_array($value)) {
				// Multi Dimensional Array
				$temp[] = arrayToJSObject($value, $jsKey, true);
			} else {
				if (is_numeric($value)) {
					$jsKey .= "$value";
				} elseif (is_bool($value)) {
					$jsKey .= ($value ? 'true' : 'false') . "";
				} elseif ($value === NULL) {
					$jsKey .= "null";
				} else {
					static $pattern = array("\\", "'", "\r", "\n");
					static $replace = array('\\', '\\\'', '\r', '\n');
					$jsKey .= "'" . str_replace($pattern, $replace, $value) . "'";
				}
				$temp[] = $jsKey;
			}
		}
		$jsArray .= implode(',', $temp);

		$jsArray .= "}\n";
		return $jsArray;
	}
}
